<template>
  <div class="header">
    <login-head title="联合登录"/>
  </div>
  <div class="body">
    <callback-form v-if="!loading"/>
    <loading v-else
             height="500px"/>
  </div>
  <login-footer class="footer"/>
</template>

<script lang="ts"
        setup>
import {QQLogin} from '@/api/login'
import Loading from '@/components/library/Loading.vue'
import LoginFooter from '@/components/library/LoginFooter.vue'
import LoginHead from '@/components/library/LoginHead.vue'
import message from '@/components/library/Message/index'
import {useCartStore} from '@/stores/cart'
import {useCommonStore} from '@/stores/common'
import {useUserStore} from '@/stores/user'
import type {UserInfo} from '@/types/user'
import CallbackForm from '@/views/login/callback/components/CallbackForm.vue'
import {onMounted, provide, ref} from 'vue'
import {useRoute, useRouter} from 'vue-router'


let loading = ref<boolean>(true)
let route = useRoute()
let router = useRouter()
let store = useCommonStore()

let unionId = ref<string>('')
provide('unionId', unionId)
let getUnionId = (): Promise<string> => {
  return new Promise((resolve) => {
    window.QC.Login.getMe((openId: string) => {
      resolve(openId)
    })
  })
}

onMounted(async () => {
  // 检查QQ是否已登录
  if (!window.QC.Login.check()) return message.error('页面错误，请刷新重试')

  // 获取unionId
  unionId.value = await getUnionId()
  // 没有unionId，退出
  if (!unionId.value) return message.error('页面错误，请刷新重试')

  // 尝试登录
  let res: any = await QQLogin(unionId.value)
  if (res.result) {
    // 保存登录信息
    useUserStore().userInfo = <UserInfo>res.result
    message.success('QQ登录成功')
    // 初始化购物车
    await useCartStore().initCart()
    await router.push(store.redirect || '/')
  } else {
    // 登录失败 说明QQ号未与任何账号绑定
    loading.value = false
  }
})
</script>

<style lang="less"
       scoped>
.header, .footer {
  background-color: white;
}

.body {
  margin: 20px;
}
</style>